package server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.Socket;

import javax.naming.InitialContext;

public class myProcess extends Thread{
	Socket socket;
	BufferedReader bufferedReader;
	PrintStream printStream;
	public final static String ROOT = "D:\\projects\\";
	myProcess(Socket socket){
		this.socket=socket;
		init();
	}
	
	private void init(){
		try {
			InputStream inputStream = this.socket.getInputStream();
			printStream = new PrintStream(this.socket.getOutputStream());
			bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
			//bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		String filename = process();
		if (filename!=null) {
			sendFile(filename);	
		}
		
		
	}
	private String process(){
		String filename = null;
		try {
			String readLine = bufferedReader.readLine();
			if (readLine==null) {
				System.out.println("readLine为空");
				return null;
			}
			String[] content = readLine.split(" ");
			
			if(content.length!=3){
				sendErrorMessage(400,"Clinet query error!");
				return null;
			}
			filename = content[1];
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return filename;
		
	}
	private void sendFile(String filename) {
		File file = new File(myProcess.ROOT+filename);
		if(!file.exists()){
			sendErrorMessage(400, "File Not Found");
		}
		
		try {
			System.out.println("进入sendfile");
			InputStream in = new FileInputStream(file);
			byte content[] = new byte[(int)file.length()];
			in.read(content);
			printStream.println("HTTP/1.0 200 Query File");
			printStream.println("content-length:"+content.length);
			printStream.println();
			printStream.write(content);
			printStream.flush();
			printStream.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		
	}

	private void sendErrorMessage(int errorCode, String errorMessage) {
		printStream.println("HTTP/1.0 "+errorCode+" "+errorMessage);
		printStream.println("content-type: text/html");
		printStream.println();
		printStream.println("<html>");
		printStream.println("<title>Error Message");
		printStream.println("</title>");
		printStream.println("<body>");
		printStream.println("<h1>ErrorCode:"+errorCode+",ErrorMeesage:"+errorMessage);
		printStream.println("</body>");
		printStream.println("</html>");
		printStream.flush();
		printStream.close();
		try {
			bufferedReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
